<script setup>
import {ref, toRaw} from "vue";
import {message} from "ant-design-vue";
import axios from "axios";
import storage from "../../util/storage.js";
import {useRouter} from "vue-router";
import server from "../../config/server.js";
import {reactive} from 'vue';
import {useAuthStore} from "../../store/auth.js";

const router = useRouter()
const store = useAuthStore()
const formState = reactive({
  username: '',
  password: '',
});
const onFinish = values => {
  // submit
  axios({
    method: "post",
    contentType: "application/json",
    url: `${server.apiBaseUrl}/auth/user/login`,
    data: toRaw(formState),
  }).then(resp => {
    if (!resp.data.status) {
      message.warning(resp.data.msg)
      return
    }
    const user = resp.data.data
    storage.set("user", user)

    axios({
      method: "get",
      url: `${server.apiBaseUrl}/auth/user/${user.id}/auth`,
    }).then(resp=>{
      console.log("auths", resp.data.data)
      store.setAuthList(resp.data.data)
      storage.set("auth", resp.data.data)
      router.push("/home")
      message.success("登录成功")
    })
  })
};
</script>
<template>
  <div class="form">
    <a-form
        :model="formState"
        name="basic"
        :label-col="{ span: 8 }"
        :wrapper-col="{ span: 16 }"
        autocomplete="off"
        @finish="onFinish"
    >
      <a-form-item
          label="账号"
          name="username"
          :rules="[{ required: true, message: '账号不能为空！' }]"
      >
        <a-input v-model:value="formState.username"/>
      </a-form-item>

      <a-form-item
          label="密码"
          name="password"
          :rules="[{ required: true, message: '密码不能为空！' }]"
      >
        <a-input-password v-model:value="formState.password"/>
      </a-form-item>

      <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
        <a-button type="primary" html-type="submit">登录</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>
<style scoped>
.form {
  width: 300px;
  margin: 10% auto;
}
</style>